<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Str;

class CyclicalityFormat implements Rule
{
    public $cyclicality_type;
    public $format_example;
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct($cyclicality_type = 'acad_year_term')
    {
        $this->cyclicality_type = $cyclicality_type;
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        if ($this->cyclicality_type == 'acad_year_term') {
            $this->format_example = "2020-2021 2";
            if (!Str::contains($value, ' ')) {
                return false;
            }
            [$acad_year, $term] = explode(" ", $value);
            if (!in_array($term, [1, 2])) {
                return false;
            }
            if (!Str::contains($acad_year, '-')) {
                return false;
            }
            [$year1, $year2] = explode("-", $acad_year);
            if (preg_match('/^\d{4}$/', $year1) && preg_match('/^\d{4}$/', $year2)) {
                if ($year2 - $year1 == 1) {
                    return true;
                }
            } else {
                return false;
            }
        }
        if ($this->cyclicality_type == 'acad_year') {
            $this->format_example = "2020-2021";
            if (!Str::contains($value, '-')) {
                return false;
            }
            [$year1, $year2] = explode("-", $value);
            if (preg_match("/^\d{4}$/", $year1) && preg_match("/^\d{4}$/", $year2)) {
                if ($year2 - $year1 == 1) {
                    return true;
                }
            } else {
                return false;
            }
        }

        if ($this->cyclicality_type == 'year') {
            $this->format_example = "2020";
            if (preg_match('/^\d{4}$/', $value)) {
                return true;
            }
        }
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return ':attribute 格式错误! 正确格式示例：' . $this->format_example;
    }
}
